<!-- src/views/admin/InternshipManagement.vue -->
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useAdminStore } from '../../store/admin'
import { useTeacherStore } from '../../store/teacher'
import axios from "axios";

// 配置 axios 基础 URL 和跨域设置
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.withCredentials = true  // 允许携带cookie

import {
  ElTable,
  ElTableColumn,
  ElButton,
  ElTag,
  ElMessage,
  ElPagination,
  ElRow,
  ElCol,
  ElCard,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElDescriptions,
  ElDescriptionsItem
} from 'element-plus'
import { useRouter } from 'vue-router'
import apiClient from '../../api'
import {adminApi} from "../../api/all.js";

const adminStore = useAdminStore()
const teacherStore = useTeacherStore()
const router = useRouter()

// 状态定义
const internships = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedInternship = ref({})
const teachers = ref([])

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const statusForm = reactive({
  status: ''
})

const teacherForm = reactive({
  teacherId: null
})

const mentorForm = reactive({
  mentorName: '',
  mentorPhone: '',
  mentorEmail: ''
})

// 获取实习列表
const fetchInternships = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize
    }
    const response = await adminStore.fetchInternships(params)
    internships.value = response.content || []
    pagination.total = response.totalElements || 0
  } catch (error) {
    ElMessage.error('获取实习列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取教师列表
const fetchTeachers = async () => {
  try {
    const response = await adminStore.fetchTeachers();
    // 从返回的教师列表中提取教师信息
    teachers.value = response.content || response || [];
  } catch (error) {
    ElMessage.error('获取教师列表失败: ' + error.message);
  }
}

const handleTeacherInput = (value) => {
  // 如果输入的是数字，直接设置为 teacherId
  if (!isNaN(value) && value !== '') {
    teacherForm.teacherId = parseInt(value)
  } else {
    teacherForm.teacherId = null
  }
}

// 查看实习详情
const viewInternshipDetail = async (internshipId) => {
  try {
    const response = await apiClient.get(`/internships/${internshipId}`)
    selectedInternship.value = response.data

    // 填充表单数据
    statusForm.status = response.data.status
    teacherForm.teacherId = response.data.teacherId
    mentorForm.mentorName = response.data.mentorName || ''
    mentorForm.mentorPhone = response.data.mentorPhone || ''
    mentorForm.mentorEmail = response.data.mentorEmail || ''

    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取实习详情失败: ' + error.message)
  }
}

// 更新实习状态
const updateInternshipStatus = async () => {
  try {
    await apiClient.put(`/internships/${selectedInternship.value.id}/status?status=${statusForm.status}`)
    ElMessage.success('实习状态更新成功')
    detailDialogVisible.value = false
    fetchInternships() // 刷新列表
  } catch (error) {
    ElMessage.error('更新实习状态失败: ' + error.message)
  }
}

// 分配指导教师
const assignTeacher = async () => {
  try {
    const response = await adminApi.assignTeacher(selectedInternship.value.id, teacherForm.teacherId);
    ElMessage.success('指导教师分配成功')
    detailDialogVisible.value = false
    fetchInternships() // 刷新列表
  } catch (error) {
    ElMessage.error('分配指导教师失败: ' + (error.response?.data?.message || error.message))
  }
}

// 更新企业导师信息
const updateMentorInfo = async () => {
  try {
    const response = await adminApi.updateMentorInfo(selectedInternship.value.id, {
      mentorName: mentorForm.mentorName,
      mentorPhone: mentorForm.mentorPhone,
      mentorEmail: mentorForm.mentorEmail
    });
    ElMessage.success('企业导师信息更新成功')
    detailDialogVisible.value = false
    fetchInternships() // 刷新列表
  } catch (error) {
    ElMessage.error('更新企业导师信息失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取实习状态标签类型
const getInternshipStatusType = (status) => {
  switch (status) {
    case 0: return 'info'     // 未开始
    case 1: return 'warning'  // 进行中
    case 2: return 'success'  // 已完成
    default: return ''
  }
}

// 获取实习状态标签文本
const getInternshipStatusLabel = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已完成'
    default: return '未知'
  }
}

const getCurrentTeacherName = () => {
  if (!teacherForm.teacherId) return '';
  const teacher = teachers.value.find(t => t.id === teacherForm.teacherId);
  return teacher ? teacher.name : '';
}

// 分页事件处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchInternships()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchInternships()
}

// 初始化加载
onMounted(() => {
  fetchInternships()
  fetchTeachers()
})
</script>

<template>
  <div class="internship-management">
    <div class="header">
      <h2>实习管理</h2>
      <el-button @click="$router.back()" style="margin-left: auto;">返回上级</el-button>
    </div>

    <!-- 实习列表 -->
    <el-table
        :data="internships"
        v-loading="loading"
        style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="studentName" label="学生姓名" min-width="100" />
      <el-table-column prop="teacherName" label="指导教师" min-width="100" />
      <el-table-column prop="companyName" label="企业名称" min-width="120" />
      <el-table-column prop="positionTitle" label="岗位名称" min-width="150" />
      <el-table-column prop="startDate" label="开始日期" width="120">
        <template #default="scope">
          {{ scope.row.startDate ? new Date(scope.row.startDate).toLocaleDateString() : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="endDate" label="结束日期" width="120">
        <template #default="scope">
          {{ scope.row.endDate ? new Date(scope.row.endDate).toLocaleDateString() : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="mentorName" label="企业导师" width="100" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getInternshipStatusType(scope.row.status)">
            {{ getInternshipStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewInternshipDetail(scope.row.id)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 实习详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="实习详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="实习ID">{{ selectedInternship.id }}</el-descriptions-item>
        <el-descriptions-item label="学生姓名">{{ selectedInternship.studentName }}</el-descriptions-item>
        <el-descriptions-item label="企业名称">{{ selectedInternship.companyName }}</el-descriptions-item>
        <el-descriptions-item label="岗位名称">{{ selectedInternship.positionTitle }}</el-descriptions-item>
        <el-descriptions-item label="指导教师">{{ selectedInternship.teacherName || '未分配' }}</el-descriptions-item>
        <el-descriptions-item label="企业导师">{{ selectedInternship.mentorName || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">
          {{ selectedInternship.startDate ? new Date(selectedInternship.startDate).toLocaleDateString() : '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="结束日期">
          {{ selectedInternship.endDate ? new Date(selectedInternship.endDate).toLocaleDateString() : '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ selectedInternship.createdAt ? new Date(selectedInternship.createdAt).toLocaleString() : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ selectedInternship.updatedAt ? new Date(selectedInternship.updatedAt).toLocaleString() : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">
          <el-tag :type="getInternshipStatusType(selectedInternship.status)">
            {{ getInternshipStatusLabel(selectedInternship.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 状态更新表单 -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>更新实习状态</span>
          </div>
        </template>
        <el-form :model="statusForm" label-width="100px">
          <el-form-item label="实习状态">
            <el-select v-model="statusForm.status" placeholder="请选择状态">
              <el-option label="未开始" :value="0"></el-option>
              <el-option label="进行中" :value="1"></el-option>
              <el-option label="已完成" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateInternshipStatus">更新状态</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 分配指导教师表单 -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>分配指导教师</span>
          </div>
        </template>
        <el-form :model="teacherForm" label-width="100px">
          <el-form-item label="指导教师">
            <!-- 修改为支持手动输入和下拉选择的形式 -->
            <el-select
                v-model="teacherForm.teacherId"
                placeholder="请选择或输入教师ID"
                clearable
                filterable
                allow-create
                default-first-option
                @input="handleTeacherInput"
            >
              <el-option
                  v-for="teacher in teachers"
                  :key="teacher.id"
                  :label="`${teacher.name} (${teacher.title || '教师'})`"
                  :value="teacher.id"
              ></el-option>
            </el-select>
            <div class="teacher-info" v-if="teacherForm.teacherId">
              <span>当前选择教师: {{ getCurrentTeacherName() }}</span>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="assignTeacher">分配教师</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 企业导师信息表单 -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>企业导师信息</span>
          </div>
        </template>
        <el-form :model="mentorForm" label-width="100px">
          <el-form-item label="导师姓名">
            <el-input v-model="mentorForm.mentorName" placeholder="请输入导师姓名"></el-input>
          </el-form-item>
          <el-form-item label="导师电话">
            <el-input v-model="mentorForm.mentorPhone" placeholder="请输入导师电话"></el-input>
          </el-form-item>
          <el-form-item label="导师邮箱">
            <el-input v-model="mentorForm.mentorEmail" placeholder="请输入导师邮箱"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateMentorInfo">更新导师信息</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.internship-management {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
/* 添加教师信息显示样式 */
.teacher-info {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}
</style>
